#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Script to run dcdc loading test, using source meter
as DCDC loading and DMM to measure DCDC output voltage
"""

import serial
import time

SOURCE_METER_DEV = "/dev/ttyUSB1"
DMM_DEV = "/dev/ttyUSB0"
BUFFER_LEN = 1024

class SCPI():
    """
    Source meter class
    """
    def __init__(self, port, timeout=2, stop=1, baudrate=9600, reset=True):
        # open serial port
        # baudrate: 9600
        # timeout 1s
        self.com = serial.Serial(
                port, 
                timeout=timeout, 
                stopbits=stop, 
                baudrate=baudrate
        )
        if reset:
            self.reset()

    def send(self, cmd):
        """
        Send out a command, will automaticlly add \n
        at the end of command
        """
        if not cmd.endswith("\n"):
            cmd += "\n"
        return self.com.write(cmd.encode())

    def query(self, cmd, decode=True):
        self.send(cmd)
        echo = self.com.read(BUFFER_LEN)
        if decode: 
            try:
                # try to decode to utf8
                echo = echo.decode()
                # try to decode to float
                echo = float(echo)
            except:
                pass
        return echo
    def reset(self):
        return self.send("*RST")

    def close(self):
        return self.com.close()


def dcdc_loading():
    sm = SCPI(SOURCE_METER_DEV)
    dmm = SCPI(DMM_DEV, stop=2)
    # init source meter to current source
    sm.send(":OUTP OFF")
    sm.send(":ROUT:TERM REAR")
    sm.send(":SOUR:FUNC CURR")
    sm.send(":SOUR:CURR:RANG:AUTO ON")
    sm.send(":SOUR:CURR:LEV 0")
    sm.send(":OUTP ON")
    # init dmm
    dmm.send("SYST:REM")
    dmm.query("MEAS:CURR:DC? AUTO")
    for i in range(100):
        # set current source
        sm.send("SOUR:CURR:LEV " + str(i/100))
        # read result
        time.sleep(1)
        print(dmm.query("READ?"))
    sm.send(":OUTP OFF")
    sm.close()
    dmm.close()

dcdc_loading()

    


